package com.cftpay.payexperience.usage.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cftpay.payexperience.R;
import com.cftpay.payexperience.usage.adapter.PayTypeAdapter;
import com.cftpay.payexperience.usage.util.ChannelPrice;
import com.cftpay.payexperience.usage.util.NetworkUtil;
import com.cftpay.payexperience.usage.util.PayToastUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import sdk.pay.PayUtil;
import sdk.pay.listener.PayGetPayStatusListener;
import sdk.pay.listener.PayGetPayTypeListener;
import sdk.pay.listener.PayUtilCallBack;
import sdk.pay.model.PayTypeModel;
import sdk.pay.model.TokenParam;
import sdk.pay.utils.PayMD5Util;

import static com.cftpay.payexperience.usage.constant.PayConstant.PRICEFAILURE;
import static com.cftpay.payexperience.usage.constant.PayConstant.PRICESUCCEED;


public class PayActivity extends Activity implements PayUtilCallBack {
    private int mCheckedId = -1;
    private ImageView oldCheckedView;
    private ListView junpay_listview;
    private PayUtil junPayUtils;
    protected Dialog mProgressDialog;
    private TextView mTextViewMoney;
    private boolean isPaying;
    // user define
    public static final String SYSTEM_NAME = "jft";
    public static final String CODE = "10207901";
    public static final String APPID = "20160905103100684424";
    public static final String COM_KEY = "2B6D1F9FFBC59376E4ED263D1663FAAF";
    public static final String KEY = "39b95c7de428d419427481d61d03f3fb";
    public static final String VECTOR = "df263ad46b25a017";
    private static final String RETURN_URL = "http://shangjia.jtpay.com/Form/TestReturn";
    private static final String NOTICE_URL = "http://shangjia.jtpay.com/Form/TestNotice";
    private String type;
    private android.os.Handler mHandler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PRICESUCCEED:
                    String goodsPrice = msg.obj.toString();
                    mTextViewMoney.setText(goodsPrice);
                    pay();
                    break;
                case PRICEFAILURE:
                    dismiss();
                    break;
            }

        }
    };
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            dismiss();
            if (junPayUtils.getPayTypeModels().size() > 0) {
                junpay_listview.setVisibility(View.VISIBLE);
                PayTypeAdapter adapter = new PayTypeAdapter(PayActivity.this, junPayUtils.getPayTypeModels());
                junpay_listview.setAdapter(adapter);
                junpay_listview.post(new Runnable() {
                    // set default choice
                    @Override
                    public void run() {
                        if (mCheckedId == -1) {
                            for (PayTypeModel typeModel : junPayUtils.getPayTypeModels()) {
                                if (typeModel.getTypeid() == 4) {
                                    mCheckedId = junPayUtils.getPayTypeModels().indexOf(typeModel);
                                    break;
                                } else {
                                    mCheckedId = 0;
                                }
                            }
                        }
                        oldCheckedView = (ImageView) junpay_listview.getChildAt(mCheckedId).findViewById(R.id.image_checked);
                        oldCheckedView.setImageResource(R.drawable.icon_radio_button_yes);
                    }
                });
            } else {
                junpay_listview.setVisibility(View.GONE);
                PayToastUtil.showMessage(PayActivity.this, "Did not get the payment!");
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.junpaylayout);
        initWidgets();
        initPay();
    }

    @Override
    protected void onResume() {
        super.onResume();
        junPayUtils.getPayStatus(new PayGetPayStatusListener() {
            @Override
            public void onPayStatus(int payStatus) {
                if (payStatus == SUCCESS) {
                    PayToastUtil.showMessage(PayActivity.this, getString(R.string.pay_success));
                } else {
                    PayToastUtil.showMessage(PayActivity.this, getString(R.string.pay_failure));
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismiss();
    }

    @Override
    protected void onDestroy() {
        if (null != junPayUtils) {
            junPayUtils.destroy();
        }
        super.onDestroy();
    }

    private void initPay() {
        Intent intent = getIntent();
        try {
            Bundle bundle = intent.getExtras();
            type = bundle.getString("type");
        } catch (Exception e) {
            e.printStackTrace();
            type = "3";
        }
        TextView isOpenWeChat = (TextView) findViewById(R.id.is_open_wechat);
        if ("1".equals(type)) {
            isOpenWeChat.setVisibility(View.VISIBLE);
        } else {
            isOpenWeChat.setVisibility(View.INVISIBLE);
        }
        junPayUtils = new PayUtil(this, this, true);
        junPayUtils.setPayParam(APPID, KEY, VECTOR, SYSTEM_NAME);
        showDialog();
        mProgressDialog.setCanceledOnTouchOutside(false);
        new ChannelPrice().ChannelPrice(this, CODE, type, mHandler);
    }

    private void pay() {
        if (NetworkUtil.isNetworkAvailable(this)) {
            junPayUtils.getToken(getTokenParam(), new PayGetPayTypeListener() {
                @Override
                public void onPayDataResult() {
                    runOnUiThread(mRunnable);
                }
            });
        } else {
            PayToastUtil.showMessage(this, getString(R.string.network_not_connected));
        }
    }

    private TokenParam getTokenParam() {
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String textKey = COM_KEY;
        String p1_usercode = CODE;
        String p2_order = dateFormat.format(date);
        String p3_money = mTextViewMoney.getText().toString();
        String p4_returnurl = RETURN_URL; // user define
        String p5_notifyurl = NOTICE_URL; // user define
        String p6_ordertime = dateFormat.format(date);
        String p7_sign = PayMD5Util.getMD5(
                p1_usercode + "&" + p2_order + "&" + p3_money + "&"
                        + p4_returnurl + "&" + p5_notifyurl + "&"
                        + p6_ordertime + textKey).toUpperCase();

        TokenParam tokenParam = new TokenParam();
        tokenParam.setP1_usercode(p1_usercode);
        tokenParam.setP2_order(p2_order);
        tokenParam.setP3_money(p3_money);
        tokenParam.setP4_returnurl(p4_returnurl);
        tokenParam.setP5_notifyurl(p5_notifyurl);
        tokenParam.setP6_ordertime(p6_ordertime);
        tokenParam.setP7_sign(p7_sign);
        tokenParam.setExtPayTypeForms(type);
        return tokenParam;
    }

    private void initWidgets() {
        junpay_listview = (ListView) findViewById(R.id.junpay_listview);
        ImageView junpay_button_submit = (ImageView) findViewById(R.id.iv_submit);
        mTextViewMoney = (TextView) findViewById(R.id.tv_money);
        junpay_button_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCheckedId >= 0) {
                    showDialog();
                    int typeId = getTypeId(mCheckedId);
                    junPayUtils.getPayParam(typeId);
                    isPaying = true;
                } else {
                    PayToastUtil.showMessage(PayActivity.this, "Payment has not yet chosen");
                }
            }
        });
        junpay_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mCheckedId != -1 && oldCheckedView != null) {
                    oldCheckedView.setImageResource(R.drawable.icon_radio_button_no);
                }
                oldCheckedView = (ImageView) view.findViewById(R.id.image_checked);
                oldCheckedView.setImageResource(R.drawable.icon_radio_button_yes);
                mCheckedId = position;
            }
        });
    }

    private int getTypeId(int index) {
        List<PayTypeModel> list = junPayUtils.getPayTypeModels();
        PayTypeModel model = list.get(index);
        return model.getTypeid();
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void showDialog() {
        if (null != mProgressDialog) {
            mProgressDialog.show();
        } else {
            mProgressDialog = ProgressDialog.show(this, "",
                    getString(R.string.pay_info), false, true, null);
        }
    }

    @Override
    public void onPayException(String s) {

    }
}